package admin

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"
	"strings"

	"github.com/google/uuid"
	"github.com/labstack/echo/v4"
	"techoiceness.com/aiagent/llm-gateway/internal/entity"
	"techoiceness.com/aiagent/llm-gateway/internal/repository"
	"techoiceness.com/aiagent/llm-gateway/internal/server/response"
)

// CreateLLMProvider 创建 LLM 提供商
func (h *AdminHandler) CreateLLMProvider(c echo.Context) error {
	var req CreateLLMProviderRequest
	if err := c.Bind(&req); err != nil {
		return response.BadRequest(c, "Invalid request format")
	}

	// 验证必填字段
	if req.Name == "" || req.ProviderType == "" || req.BaseURL == "" || req.APIKey == "" {
		return response.BadRequest(c, "Missing required fields")
	}

	// 解析配置
	var config entity.ProviderConfig
	if req.Config != nil {
		configBytes, err := json.Marshal(req.Config)
		if err != nil {
			return response.BadRequest(c, "Invalid config format")
		}
		if err := json.Unmarshal(configBytes, &config); err != nil {
			return response.BadRequest(c, "Invalid config format")
		}
	}

	// 解析模型信息
	var models []entity.ModelInfo
	if req.Models != nil {
		modelsBytes, err := json.Marshal(req.Models)
		if err != nil {
			return response.BadRequest(c, "Invalid models format")
		}
		if err := json.Unmarshal(modelsBytes, &models); err != nil {
			return response.BadRequest(c, "Invalid models format")
		}
	}

	// 创建提供商实体
	provider := &entity.LLMProvider{
		Name:         req.Name,
		ProviderType: req.ProviderType,
		BaseURL:      req.BaseURL,
		APIKey:       req.APIKey,
		IsEnabled:    req.IsEnabled,
		IsDefault:    req.IsDefault,
		Description:  req.Description,
	}

	// 序列化配置和模型信息
	if len(models) > 0 {
		modelsJSON, _ := json.Marshal(models)
		provider.Models = modelsJSON
	}

	configJSON, _ := json.Marshal(config)
	provider.Config = configJSON

	// 保存到数据库
	if err := h.repos.GetLLMProvider().CreateProvider(context.Background(), provider); err != nil {
		return response.InternalServerError(c, "Failed to create provider")
	}

	h.llmProviderManager.LoadAvailable(context.Background())

	return response.Success(c, provider)
}

// GetLLMProviders 获取 LLM 提供商列表
func (h *AdminHandler) GetLLMProviders(c echo.Context) error {
	// 解析查询参数
	pageSizeStr := c.QueryParam("page_size")
	pageStr := c.QueryParam("page")
	isEnabledStr := c.QueryParam("is_enabled")
	providerType := c.QueryParam("provider_type")

	var queryOptions repository.LLMProviderQueryOptions

	if pageSizeStr != "" {
		if l, err := strconv.Atoi(pageSizeStr); err == nil {
			queryOptions.PageSize = l
		}
	} else {
		queryOptions.PageSize = 10
	}

	if pageStr != "" {
		if o, err := strconv.Atoi(pageStr); err == nil {
			queryOptions.Page = o
		}
	} else {
		queryOptions.Page = 1
	}

	if isEnabledStr != "" {
		if a, err := strconv.ParseBool(isEnabledStr); err == nil {
			queryOptions.IsEnabled = &a
		}
	}

	if providerType != "" {
		queryOptions.ProviderType = providerType
	}

	// 根据查询参数选择不同的查询方法
	dbResult, err := h.repos.GetLLMProvider().QueryProviders(context.Background(), queryOptions)
	if err != nil {
		return response.InternalServerError(c, "Failed to get providers")
	}

	// 转换为响应格式
	var providerResponses []LLMProviderDetail
	for _, provider := range dbResult.Providers {
		providerResponse := LLMProviderDetail{
			ID:           provider.ID,
			Name:         provider.Name,
			ProviderType: provider.ProviderType,
			BaseURL:      provider.BaseURL,
			IsEnabled:    provider.IsEnabled,
			IsDefault:    provider.IsDefault,
			Description:  provider.Description,
			CreatedAt:    provider.CreatedAt,
			UpdatedAt:    provider.UpdatedAt,
		}

		// 解析配置
		if provider.Config != nil {
			var config entity.ProviderConfig
			if err := json.Unmarshal(provider.Config, &config); err == nil {
				providerResponse.Config = &config
			}
		}

		// 解析模型信息
		if provider.Models != nil {
			var models []entity.ModelInfo
			if err := json.Unmarshal(provider.Models, &models); err == nil {
				providerResponse.Models = models
			}
		}

		providerResponses = append(providerResponses, providerResponse)
	}

	return response.Success(c, map[string]interface{}{
		"rows":      providerResponses,
		"total":     dbResult.Total,
		"page":      dbResult.Page,
		"page_size": dbResult.PageSize,
	})
}

// GetLLMProvider 获取单个 LLM 提供商
func (h *AdminHandler) GetLLMProvider(c echo.Context) error {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		return response.BadRequest(c, "Invalid provider ID")
	}

	provider, err := h.repos.GetLLMProvider().GetProviderByID(context.Background(), id)
	if err != nil {
		return response.NotFound(c, "Provider not found")
	}

	// 转换为响应格式
	providerResponse := LLMProviderDetail{
		ID:           provider.ID,
		Name:         provider.Name,
		ProviderType: provider.ProviderType,
		BaseURL:      provider.BaseURL,
		IsEnabled:    provider.IsEnabled,
		IsDefault:    provider.IsDefault,
		Description:  provider.Description,
		CreatedAt:    provider.CreatedAt,
		UpdatedAt:    provider.UpdatedAt,
	}

	// 解析配置
	if provider.Config != nil {
		var config entity.ProviderConfig
		if err := json.Unmarshal(provider.Config, &config); err == nil {
			providerResponse.Config = &config
		}
	}

	// 解析模型信息
	if provider.Models != nil {
		var models []entity.ModelInfo
		if err := json.Unmarshal(provider.Models, &models); err == nil {
			providerResponse.Models = models
		}
	}

	return response.Success(c, providerResponse)
}

// UpdateLLMProvider 更新 LLM 提供商
func (h *AdminHandler) UpdateLLMProvider(c echo.Context) error {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		return response.BadRequest(c, "Invalid provider ID")
	}

	var req UpdateLLMProviderRequest
	if err := c.Bind(&req); err != nil {
		return response.BadRequest(c, "Invalid request format")
	}

	// 获取现有提供商
	provider, err := h.repos.GetLLMProvider().GetProviderByID(context.Background(), id)
	if err != nil {
		return response.NotFound(c, "Provider not found")
	}

	// 更新字段
	if req.Name != nil && strings.TrimSpace(*req.Name) != "" {
		provider.Name = *req.Name
	}
	if req.BaseURL != nil && strings.TrimSpace(*req.BaseURL) != "" {
		provider.BaseURL = *req.BaseURL
	}
	if req.APIKey != nil && strings.TrimSpace(*req.APIKey) != "" {
		provider.APIKey = *req.APIKey
	}
	if req.IsEnabled != nil {
		provider.IsEnabled = *req.IsEnabled
	}
	if req.Description != nil {
		provider.Description = *req.Description
	}

	// 更新配置
	if req.Config != nil {
		configBytes, err := json.Marshal(req.Config)
		if err != nil {
			return response.BadRequest(c, "Invalid config format")
		}
		provider.Config = configBytes
	}

	// 更新模型信息
	if req.Models != nil {
		modelsBytes, err := json.Marshal(req.Models)
		if err != nil {
			return response.BadRequest(c, "Invalid models format")
		}
		provider.Models = modelsBytes
	}

	// 保存更新
	if err := h.repos.GetLLMProvider().UpdateProvider(context.Background(), provider); err != nil {
		return response.InternalServerError(c, "Failed to update provider")
	}

	// 如果设置为默认提供商，更新默认状态
	if req.IsDefault != nil {
		if err := h.repos.GetLLMProvider().SetProviderDefault(context.Background(), id, *req.IsDefault); err != nil {
			errorMessage := fmt.Sprintf("设置默认提供商失败: %v", err)
			return response.InternalServerError(c, errorMessage)
		}
	}

	// 刷新provider管理器，使配置变更生效
	if h.llmProviderManager != nil {
		if err := h.llmProviderManager.LoadAvailable(context.Background()); err != nil {
			errorMessage := fmt.Sprintf("刷新提供商管理器失败: %v", err)
			return response.InternalServerError(c, errorMessage)
		}
	}

	return response.Success(c, provider)
}

// DeleteLLMProvider 删除 LLM 提供商
func (h *AdminHandler) DeleteLLMProvider(c echo.Context) error {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		return response.BadRequest(c, "Invalid provider ID")
	}

	if err := h.repos.GetLLMProvider().DeleteProvider(context.Background(), id); err != nil {
		return response.InternalServerError(c, "Failed to delete provider")
	}

	return response.Success(c, "Provider deleted successfully")
}

// SetLLMProviderDefault 设置提供商默认状态
func (h *AdminHandler) SetLLMProviderDefault(c echo.Context) error {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		return response.BadRequest(c, "无效的提供商ID")
	}

	if err := h.repos.GetLLMProvider().SetProviderDefault(context.Background(), id, true); err != nil {
		errorMessage := fmt.Sprintf("设置默认提供商失败: %v", err)
		return response.InternalServerError(c, errorMessage)
	}

	// 刷新provider管理器，使新的默认provider生效
	if h.llmProviderManager != nil {
		if err := h.llmProviderManager.LoadAvailable(context.Background()); err != nil {
			return response.InternalServerError(c, "刷新提供商管理器失败")
		}
	}

	return response.Success(c, "设置默认提供商成功")
}

// SetLLMProviderEnabled 设置提供商启用状态
func (h *AdminHandler) SetLLMProviderEnabled(c echo.Context) error {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		return response.BadRequest(c, "Invalid provider ID")
	}

	var req SetLLMProviderEnabledRequest
	if err := c.Bind(&req); err != nil {
		return response.BadRequest(c, "Invalid request format")
	}

	if err := h.repos.GetLLMProvider().SetProviderEnabled(context.Background(), id, req.IsEnabled); err != nil {
		return response.InternalServerError(c, "Failed to toggle provider status")
	}

	// 刷新provider管理器，使状态变更生效
	if h.llmProviderManager != nil {
		if err := h.llmProviderManager.LoadAvailable(context.Background()); err != nil {
			return response.InternalServerError(c, "Failed to refresh provider manager")
		}
	}

	return response.Success(c, "Provider status toggled successfully")
}
